package com.ruoyi.framework.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.config.QiNiuYunConfig;
import com.ruoyi.framework.redis.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Paths;

@Component
public class QiNiuYunUtils {


    @Autowired
    private QiNiuYunConfig qiNiuYunConfig;

    /*上传方法 使用*/
    public String scyGet(MultipartFile file, String key) {

        Configuration cfg = getConfiguration();
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //文件原始名和随机数uuid拼接以防名字重复
        try {
            //byte[]数组方式读取文件；
            byte[] uploadBytes = file.getBytes();
            //读取
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            //申请七牛云成功后用户独有的两个识别符
            Auth auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());

            //资源存储的空间在七牛云中的空间
            String upToken = auth.uploadToken(qiNiuYunConfig.getBucket());
            try {
                //上传七牛云                                              资源                    文件名  空间
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                //返回的文件名
                System.out.println("七牛云返回链接图片putRet.key =" + putRet.key);
                //返回内部名称
                System.out.println("七牛云返回链接图片putRet.hash=" + putRet.hash);

                response.close();
                byteInputStream.close();

                return putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                return Constants.StrStatusUtils.one;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Constants.StrStatusUtils.three;
        }

    }

    /**
     * 网络将图片上传到七牛云 弃用
     */
    public String uploadQNImg(FileInputStream file, String key) {

        Configuration cfg = getConfiguration();
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成上传凭证，然后准备上传
        try {
            Auth auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());
            String upToken = auth.uploadToken(qiNiuYunConfig.getBucket());
            try {
                Response response = uploadManager.put(file, key, upToken, null, null);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                String returnPath = putRet.key;
                return returnPath;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());

                try {
                    System.err.println(r.bodyString());
                    return Constants.StrStatusUtils.one;
                } catch (QiniuException ex2) {
                    return Constants.StrStatusUtils.two;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Constants.StrStatusUtils.three;
        }
    }


    /**
     * 普通文件名路径上传  未使用
     *
     * @param tape
     * @return
     */
    public String uploadQN(String tape) {

        String key_name;

        Configuration cfg = getConfiguration();

        String queen = tape.substring(tape.lastIndexOf("."));
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString() + queen;

        Auth auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());
        String upToken = auth.uploadToken(qiNiuYunConfig.getBucket());

        String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), qiNiuYunConfig.getBucket()).toString();
        try {
            //设置断点续传文件进度保存目录
            FileRecorder fileRecorder = new FileRecorder(localTempDir);
            UploadManager uploadManager = new UploadManager(cfg, fileRecorder);

            Response response = uploadManager.put(tape, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            System.out.println(putRet.key);
            System.out.println(putRet.hash);

            key_name = putRet.key;

        } catch (IOException ex) {
            ex.printStackTrace();

            key_name = "";
        }
        return key_name;
    }


    /**
     * 七牛云删除信息方法
     *
     * @param key
     * @return
     */
    public Integer getDelete(String key) {

        Configuration cfg = getConfiguration();

        //...其他参数参考类注释
        Auth auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());

        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {

            bucketManager.delete(qiNiuYunConfig.getBucket(), key);

        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            //System.err.println(ex.response.toString());
            return ex.code();
            //return 200;
        }
        return 200;
    }


    /**
     * 观看图片链接
     *
     * @param tableName
     * @param
     * @return
     */
    public String getUrlImg(String tableName) {
        /*如果 连接本身没有值 返回空*/
        if (StringUtils.isEmpty(tableName) ||
                StringUtils.isEmpty(qiNiuYunConfig.getUrl()) ||
                StringUtils.isEmpty(qiNiuYunConfig.getSecretKey()) ||
                StringUtils.isEmpty(qiNiuYunConfig.getAccessKey())
        ) {
            return "/img/timg.jpg";
        }
        String finalUrl = "";
        try {

            String encodedFileName = URLEncoder.encode(tableName, "utf-8").replace("+", "%20");

            String publicUrl = String.format("%s/%s", qiNiuYunConfig.getUrl(), encodedFileName);
            Auth auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());

            finalUrl = auth.privateDownloadUrl(publicUrl, RedisKey.time + 10000);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return finalUrl;
    }

    public Configuration getConfiguration() {

        Configuration cfg = null;

        if (qiNiuYunConfig.getStatus().equals("0")) {
            /*zone.zone0意思是华东*/
            cfg = new Configuration(Zone.zone0());
        } else if (qiNiuYunConfig.getStatus().equals("1")) {
            /*zone.zone1华北*/
            cfg = new Configuration(Zone.zone1());
        } else if (qiNiuYunConfig.getStatus().equals("2")) {
            /*zone.zone2华南*/
            cfg = new Configuration(Zone.zone2());
        }

        // 其他参数参考类注释
        return cfg;
    }

}
